<?php

namespace App\Models;

use App\Admin\Traits\ModelTree as AppModelTree;
use Encore\Admin\Traits\ModelTree;
use Encore\Admin\Tree;

class Category extends BaseModel
{
    protected $table = 'categorys';

    use ModelTree, AppModelTree  {
        AppModelTree::delete insteadof ModelTree;
    }

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setParentColumn('p_id');
        $this->setOrderColumn('sort');
        $this->setTitleColumn('name');
    }

    /**
     * @param \Closure $callback
     *
     * @return Tree
     */
    public static function tree(\Closure $callback = null)
    {
        return new Tree(new static(), $callback);
    }

    /**
     * 重写Tree selectOptions方法
     * @return array
     */
    public static function selectOptions()
    {
        //根据url限制获取分类
        $url = request()->getRequestUri();
        if (strstr($url, '/admin/product'))
        {
            $options = self::where('level', '<=', 2)->get()->toArray();
        } elseif (strstr($url, '/admin/category')) {
            $options = self::where('level', '<=', 4)->get()->toArray();
        } else {
            $options = self::all()->toArray();
        }

        if (!empty($options))
            $options = (new static())->buildSelectOptions($options);

        return collect($options)->all();
    }


    public function products()
    {
        return $this->hasMany(Product::class, 'category_id', 'id');
    }

    public function parent()
    {
        return $this->belongsTo(self::class, 'p_id', 'id');
    }

    public function children()
    {
        return $this->hasMany(self::class, 'p_id', 'id');
    }
}
